import { defineStore } from "pinia";
import { ref } from "vue";
import { Login } from "@/api/user";
import type { loginForm, loginReqData } from "@/api/type";
export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<string | null>(JSON.parse(localStorage.getItem("TOKEN") as string).token);
    //   登录发送请求const
    const reqLogin = async (userData: loginForm) => {
      const result: loginReqData = await Login(userData);
      console.log(result);
      if (result.code == 200) {
        // 登录成功
        // 存储token
        token.value = result.data.token;
        localStorage.setItem("TOKEN", JSON.stringify({ token: token.value }));
        return "登录成功";
      } else {
        throw result.data.message;
      }
    };
    return { token, reqLogin };
  },
  //   持续化存储
  {
    persist: {
      key: "TOKEN",
      storage: localStorage,
      paths: ["token"],
    },
  }
);
